package com.kob.backend.service.impl.user.account;

import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.account.LoginService;
import com.kob.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager; //认证管理器
    @Override
    public Map<String, String> getToken(String username, String password) {
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(username,password);//将用户名和密码进行封装后（存放的是加密之后的密码）
        //验证是否可以正常登录
        //失败会自动处理
        Authentication authentication=authenticationManager.authenticate(authenticationToken);//认证管理器接收一个封装好的认证令牌 返回一个已验证的认证
        //取出用户
        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();// 返回认证的用户登录信息
        User user = loginUser.getUser();//用户信息
        //将用户的userid封装成jwt令牌
        String jwt = JwtUtil.createJWT(user.getId().toString());
        //定义返回结果格式
        Map<String,String> map= new HashMap<>();
        map.put("error_message","success");
        map.put("token",jwt);
        return map;
    }
}
